package com.link.gateway.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 解决跨域问题
 *
 * @author guoshan
 * @date 2019-07-18 11:56
 */

@Configuration
public class CorsConfig {
    /**
     * 这里为支持的请求头，如果有自定义的header字段请自己添加
     */
    private static final String ALLOWED_HEADERS = "Content-Type,X-Requested-With,x-requested-with,accept, Origin, Link-Request-Id,"
            + "Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,authorization,APIAuthorization,"
            + "encryptdata";
    private static final String ALLOWED_METHODS = "*";
    private static final String ALLOWED_EXPOSE = "*";
    private static final String MAX_AGE = "18000";


    /**
     * 添加header，防止跨域被拦截
     *
     * @author huanglongjian
     * @date 2019-07-22 11:07
     */

    @Bean
    public WebFilter corsFilter() {
        return (ServerWebExchange ctx, WebFilterChain chain) -> {
            ServerHttpRequest request = ctx.getRequest();
            if (CorsUtils.isCorsRequest(request)) {
                ServerHttpResponse response = ctx.getResponse();
                HttpHeaders headers = response.getHeaders();
                HttpHeaders reqHeaders = request.getHeaders();
                headers.remove("Access-Control-Allow-Methods");
                headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);

                headers.remove("Access-Control-Max-Age");
                headers.add("Access-Control-Max-Age", MAX_AGE);

                headers.remove("Access-Control-Allow-Headers");
                headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS);

                headers.remove("Access-Control-Expose-Headers");
                headers.add("Access-Control-Expose-Headers", ALLOWED_EXPOSE);

                headers.remove("Access-Control-Allow-Origin");
                headers.add("Access-Control-Allow-Origin", reqHeaders.getOrigin());

                headers.remove("Access-Control-Allow-Credentials");
                headers.add("Access-Control-Allow-Credentials", "true");
                if (request.getMethod() == HttpMethod.OPTIONS) {
                    response.setStatusCode(HttpStatus.OK);
                    return Mono.empty();
                }
            }
            return chain.filter(ctx);
        };
    }
}
